package com.jiangjiang.eshop.commodity.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangjiang.eshop.commodity.convert.PropertyConvert;
import com.jiangjiang.eshop.commodity.convert.PropertyGroupConvert;
import com.jiangjiang.eshop.commodity.dao.PropertyGroupMapper;
import com.jiangjiang.eshop.commodity.domain.PropertyGroupEntity;
import com.jiangjiang.eshop.commodity.dto.PropertyGroupDTO;
import com.jiangjiang.eshop.commodity.dto.PropertyGroupRelationshipDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName PropertyGroupService
 * @Description TODO
 * @Author jhw
 * @Date 2021/6/20 16:16
 * @Version 1.0
 **/
@Service
public class PropertyGroupService extends ServiceImpl<PropertyGroupMapper, PropertyGroupEntity> {
    @Autowired
    private PropertyGroupConvert propertyGroupConvert;
    @Autowired
    private PropertyGroupRelationshipService propertyGroupRelationshipService;


    /**
     * 批量保存属性组
     * @param groupDTOList
     */
    public void saveBatch(List<PropertyGroupDTO> groupDTOList) {
        for (PropertyGroupDTO dto : groupDTOList) {
            PropertyGroupEntity entity = propertyGroupConvert.convertDTO2Entity(dto);
            this.save(entity);
            // 保存属性组和属性关联关系22
            List<PropertyGroupRelationshipDTO> relationshipDTOList = dto.getRelationshipDTOList()
                    .stream()
                    .peek(relation -> relation.setPropertyGroupId(dto.getId()))
                    .collect(Collectors.toList());
            propertyGroupRelationshipService.saveBatch(relationshipDTOList);
        }
    }

    /**
     * 根据类目查询所有的属性组
     * @param categoryId
     * @return
     */
    public List<PropertyGroupDTO> listByCategoryId(Long categoryId) {
        LambdaQueryWrapper<PropertyGroupEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PropertyGroupEntity::getCategoryId, categoryId);
        return propertyGroupConvert.convertEntities2DTOList(this.list(wrapper));
    }



    /**
     * 根据类目id删除属性组
     * @param categoryId
     */
    public void removeByCategoryId(Long categoryId) {
        LambdaQueryWrapper<PropertyGroupEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PropertyGroupEntity::getCategoryId, categoryId);
        this.remove(wrapper);
    }


}
